<?php

namespace app\model;

use \core\lib\database;
use \core\lib\session;
use \core\lib\logs;

class userModel{
	private $db;
	public function __construct(){
		$this->db = new database();
	}
	
	public function exist($name){
		$sql = "select *from `userinfo` where `username` = '{$name}'";
		$ok = $this->db->query($sql);
		return  !empty($ok);
	}
	
	public function register($name, $pass){
		$sql = "insert into userinfo (username, password) values ('{$name}', '".md5($pass)."')";
		$ok = $this->db->update($sql);
		if($ok){
			$user = ["username" => $name, "id" => $this->db->insert_id()];
			session::set("user", $user);
		}
		return $ok;
	}
	
	public function login($name, $pass){
		$sql = "select id, username from `userinfo` where `username` = '{$name}' && `password` = '".md5($pass)."'";
		$ans = $this->db->query($sql);
		if($ans != false){
			session::set("user", $ans[0]);
			logs::write($ans[0]['username'] . ' is login!', "user");
			return true;
		}
		return false;
	}
}